//
//  PhotoBrowserController.swift
//  JIMWeiBo
//
//  Created by 陈恒均 on 2018/2/24.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

private let PhotoBrowserCell = "PhotoBrowserCell"
class PhotoBrowserController: UIViewController {

    var indexPath :NSIndexPath
    var picUrls : [NSURL]
    
    
    // MARK:- 懒加载属性
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: PhotoBrowserCollectionViewLayout())
    private lazy var closeBtn : UIButton = UIButton(bgcolor: UIColor.darkGray, fontSize: 14, title: "关 闭")
    private lazy var saveBtn : UIButton = UIButton(bgcolor: UIColor.darkGray, fontSize: 14, title: "保 存")
    
    init(indexPath :NSIndexPath , picUrls : [NSURL]) {
        self.indexPath = indexPath
        self.picUrls = picUrls
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        super.loadView()
        
        view.frame.size.width += 20
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false)
        
    }
}
// MARK:- 设置UI
extension PhotoBrowserController{
    private func setupUI(){
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        // MARK:- 设置frame
        collectionView.frame = view.bounds
        closeBtn.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 90, height: 32))
        }
        
        saveBtn.snp.makeConstraints { (make) in
            make.right.equalTo(-20)
            make.bottom.equalTo(closeBtn.snp.bottom)
            make.size.equalTo(closeBtn.snp.size)
        }
        
        collectionView.register(PhotoBrowerCollectionViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCell)
        
        collectionView.dataSource = self
        
        // MARK:- 监听两个按钮的点击
        closeBtn.addTarget(self, action: #selector(PhotoBrowserController.closeBtnClick), for: .touchUpInside)
        saveBtn.addTarget(self, action: #selector(PhotoBrowserController.saveBtnClick), for: .touchUpInside)
      
    }
}
// MARK:- 时间监听
extension PhotoBrowserController{
    @objc private func closeBtnClick(){
        dismiss(animated: true, completion: nil)
    }
    

    @objc private func saveBtnClick(){
//        print("saveBtnClick")
        let cell = collectionView.visibleCells.first as! PhotoBrowerCollectionViewCell
        
        guard let image = cell.imageView.image else{
            return
        }
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(PhotoBrowserController.image(image:didFinishSavingWithError:contextInfo:)), nil)

    }

    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    @objc private func image(image : UIImage , didFinishSavingWithError error : NSError? , contextInfo : AnyObject){
        var showInfo = ""
        if error != nil{
            showInfo = "保存失败"
        }else{
            showInfo = "保存成功"
        }
        SVProgressHUD.showInfo(withStatus: showInfo)
        
    }
    
}

extension PhotoBrowserController : UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoBrowserCell, for: indexPath) as! PhotoBrowerCollectionViewCell
        
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.orange : UIColor.blue
        
        cell.picURL = picUrls[indexPath.item]
        cell.delegate = self
        return cell
        
    }
}

extension PhotoBrowserController : AnimatorDismissDelegate{
    func indexPathForDimissView() -> NSIndexPath {
        let cell = collectionView.visibleCells.first
        
        return collectionView.indexPath(for: cell!)! as NSIndexPath
    }
    
    func imageViewForDimissView() -> UIImageView {
        let imageView = UIImageView()
        
        let cell = collectionView.visibleCells.first as! PhotoBrowerCollectionViewCell
        imageView.frame = cell.imageView.frame
        imageView.image = cell.imageView.image
        
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        
        return imageView
    }
    
    
}

extension PhotoBrowserController : PhotoBrowerCollectionViewCellDelegate{
    func imageViewClick() {
        closeBtnClick()
    }
}
// MARK:- 自定义布局
class PhotoBrowserCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        itemSize = collectionView!.frame.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal

        collectionView?.isPagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}


